
package com.hlkj.pay.app.merchant.ext.impl.yftpay.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by Ricky on 2016/11/20.
 */
@Slf4j
public class HttpUtils {

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, JSONObject params) {
        StringBuilder result = new StringBuilder();
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(getRequestParamString(params), "UTF-8");

            // 设置POST请求的实体
            httpPost.setEntity(reqEntity);
            httpPost.setHeader("User-Agent", "Mozilla/5.0");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("银付通返回参数 url:{}, params:{}, response:{}", httpPost.getURI(), params, result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}, params: {}", url, params, e);
        }
        return null;
    }

    private static String getRequestParamString(JSONObject paramMap) throws UnsupportedEncodingException {
        String charset = "UTF-8";
        StringBuilder sb = new StringBuilder();

        Map<String, String> m = paramMap.toBean(Map.class);
        for (Map.Entry<String, String> entry : m.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }
            sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), charset)).append("&");
        }
        String s_ret = sb.toString();
        if (s_ret.isEmpty()) {
            return "";
        }
        s_ret = s_ret.substring(0, s_ret.length() - 1);
        return s_ret;
    }

    public static String post(String url, String body) {
        StringBuilder result = new StringBuilder();
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(body, "UTF-8");

            // 设置POST请求的实体
            httpPost.setEntity(reqEntity);
            httpPost.setHeader("Content-Type", "application/json");
            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("银付通返回参数 url:{}, params:{}, response:{}", httpPost.getURI(), "body", result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}, params: {}", url, "body", e);
        }
        return null;
    }

    public static String get(String url) {
        StringBuilder result = new StringBuilder();
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            url = HttpUtil.encodeParams(url, Charset.defaultCharset());
            // 创建HttpPost对象
            HttpGet httpPost = new HttpGet(url);

            // 设置POST请求的实体
//            httpPost.setHeader("Content-Type", "application/json");
            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("银付通返回参数 url:{}, params:{}, response:{}", httpPost.getURI(), "body", result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}, params: {}", url, "body", e);
        }
        return null;
    }

    public static void main(String[] args) {

        String json = "{\"income\":\"99\",\"payOrderId\":\"221F30pq127xXplA\",\"amount\":\"100\",\"mchId\":\"20000021\",\"productId\":\"8006\",\"mchOrderNo\":\"1744945137984\",\"paySuccTime\":\"1744945185000\",\"sign\":\"74E93345275BFA804CCD55D5D2563D37\",\"channelOrderNo\":\"2025041822001471561430097802\",\"backType\":\"2\",\"subMchId\":\"\",\"param1\":\"\",\"param2\":\"{\\\"gmt_create\\\":\\\"2025-04-18 10:59:44\\\",\\\"charset\\\":\\\"UTF-8\\\",\\\"seller_email\\\":\\\"wbtxhz@163.com\\\",\\\"gmt_payment\\\":\\\"2025-04-18 10:59:44\\\",\\\"notify_time\\\":\\\"2025-04-18 10:59:45\\\",\\\"subject\\\":\\\"测试商品\\\",\\\"sign\\\":\\\"null\\\",\\\"buyer_id\\\":\\\"2088022469071562\\\",\\\"invoice_amount\\\":\\\"1.00\\\",\\\"version\\\":\\\"1.0\\\",\\\"notify_id\\\":\\\"2025041801222105944071561440262055\\\",\\\"fund_bill_list\\\":\\\"[{\\\\\\\"amount\\\\\\\":\\\\\\\"1.00\\\\\\\",\\\\\\\"fundChannel\\\\\\\":\\\\\\\"ALIPAYACCOUNT\\\\\\\"}]\\\",\\\"notify_type\\\":\\\"trade_status_sync\\\",\\\"out_trade_no\\\":\\\"221F30pq127xXplA\\\",\\\"total_amount\\\":\\\"1.00\\\",\\\"trade_status\\\":\\\"TRADE_SUCCESS\\\",\\\"trade_no\\\":\\\"2025041822001471561430097802\\\",\\\"auth_app_id\\\":\\\"2021005104663211\\\",\\\"receipt_amount\\\":\\\"1.00\\\",\\\"buyer_logon_id\\\":\\\"391***@qq.com\\\",\\\"point_amount\\\":\\\"0.00\\\",\\\"buyer_pay_amount\\\":\\\"1.00\\\",\\\"app_id\\\":\\\"2021005104663211\\\",\\\"seller_id\\\":\\\"2088941859893811\\\"}\",\"appId\":\"\",\"status\":\"2\"}";
        HttpUtils.post("http://127.0.0.1:8024/openapi/callback/pay/order/yftpay/S1524906003", json);
//        String key = "8J5KFPK5EGJEGDSOIYMQ2CHPK1ZYWYZRON0OP4MYZZVZJRGVIDKDRWQST5LKFIGIEK5VOKGNNJOODP6WG0PTAOG2Q70BMK8ICOLI1OSBUHXF3BRADF3C61OHQNWMDMJO";
//        JSONObject paramMap = new JSONObject();
//        paramMap.set("mchId", "20000021");                               // 商户ID
//        //paramMap.put("appId", appId);                             // 应用ID,非必填
//        paramMap.set("mchOrderNo", System.currentTimeMillis());     // 商户订单号
//        paramMap.set("productId", "8006");                       // 支付产品
//        paramMap.set("amount", 100);                                // 支付金额,单位分
//        paramMap.set("currency", "cny");                            // 币种, cny-人民币
//        paramMap.set("clientIp", "211.94.116.218");                 // 用户地址,微信H5支付时要真实的
//        paramMap.set("subject", "XXPAY支付测试");
//        paramMap.set("body", "XXPAY支付测试");
//        paramMap.set("notifyUrl", "");                       // 回调URL
//
//        //{"h5_info": {"type":"Wap","wap_url": "https://pay.qq.com","wap_name": "腾讯充值"}}
//
//        String reqSign = PayDigestUtilOK.getSign(paramMap, key);
//        paramMap.set("sign", reqSign);                              // 签名
//        String reqData = "params=" + paramMap.toString();
//        System.out.println("请求支付中心下单接口,请求数据:" + reqData);
//        String url = "http://sdpay.sdwbtx.com/api/pay/create_order?" + reqData;
//        String result = HttpUtils.get(url);
//
//        System.out.println("请求支付中心下单接口,响应数据:" + result);
//        Map retMap = JSON.parseObject(result);
//        if("SUCCESS".equals(retMap.get("retCode"))) {
//            // 验签
//            String checkSign = PayDigestUtilOK.getSign(retMap, key, "sign");
//            String retSign = (String) retMap.get("sign");
//            if(checkSign.equals(retSign)) {
//                System.out.println("=========支付中心下单验签成功=========");
//            }else {
//                System.err.println("=========支付中心下单验签失败=========");
//            }
//        }
    }

}
